package org.example.controller;

import org.example.domain.Grow;
import org.example.dto.*;
import org.example.result.PageResult;
import org.example.result.Result;
import org.example.service.CropService;
import org.example.service.GrowService;
import org.example.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("crop")
public class CropController {

    @Autowired
    private CropService cropService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private GrowService growService;

    /**
     * 记录农作物
     *
     * @return
     */
    @RequestMapping("logCrop")
    public Result logCrop(GrowDto growLogDto) {
        growService.logCrop(growLogDto);
        return Result.success();
    }

    @RequestMapping("inHouse")
    public Result inHouse(CropInHouseDto cropInHouseDto) {
        growService.inHouse(cropInHouseDto);
        return Result.success();
    }

    @RequestMapping("/logList/{id}")
    public Result logList(@PathVariable("id") Integer id) {
        List<Grow> list = growService.growList(id);
        return Result.success(list);
    }

    @RequestMapping("list")
    public Result list(CropPageQueryDto cropPageQueryDto) {
        Object userId = JwtUtils.of(request.getHeader("token")).get("id");
        cropPageQueryDto.setUserId(Integer.valueOf(userId.toString()));
        PageResult pageResult = cropService.listAll(cropPageQueryDto);
        return Result.success(pageResult);
    }

    @RequestMapping("/delCrop/{id}")
    public Result delCrop(@PathVariable("id") String id) {
        cropService.delCrop(id);
        return Result.success();
    }

    /**
     * 农作新增
     *
     * @param cropSaveDto
     * @return
     */
    @RequestMapping("saveCrop")
    public Result saveCrop(CropSaveDto cropSaveDto) {
        Object userId = JwtUtils.of(request.getHeader("token")).get("id");
        cropSaveDto.setUserId(Integer.valueOf(userId.toString()));
        cropSaveDto.setCreateDate(LocalDateTime.now());
        cropService.saveCrop(cropSaveDto);
        return Result.success();
    }


}
